<template>
  <view class="post-container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-content">
        <button 
          class="nav-back" 
          @click="goBack"
          hover-class="button-hover"
        >
          <uni-icons type="left" size="20" color="#333"></uni-icons>
        </button>
        <text class="title">发布</text>
        <button 
          class="publish-btn" 
          :disabled="!canPublish" 
          :loading="isSubmitting" 
          @tap="handlePublish"
          :style="{ opacity: canPublish ? 1 : 0.5 }"
        >
          {{ isSubmitting ? '发布中...' : '发布' }}
        </button>
      </view>
    </view>

    <!-- 内容区域 -->
    <scroll-view class="content-scroll" scroll-y>
      <!-- 文本输入区 -->
      <view class="input-section">
        <input
          class="title-input"
          v-model="postForm.title"
          placeholder="标题（必填）"
          maxlength="100"
          placeholder-class="placeholder"
          @input="validateTitle"
        />
        <text class="error-tip" v-if="errors.title">{{ errors.title }}</text>
        
        <textarea
          class="content-input"
          v-model="postForm.content"
          placeholder="分享你的想法..."
          maxlength="1000"
          placeholder-class="placeholder"
          @input="validateContent"
          auto-height
        ></textarea>
        <text class="error-tip" v-if="errors.content">{{ errors.content }}</text>
      </view>

      <!-- 图片上传区 -->
      <view class="upload-section">
        <view class="image-list">
          <view 
            class="image-item" 
            v-for="(image, index) in postForm.images" 
            :key="index"
          >
            <image :src="image" mode="aspectFill" @tap="previewImage(index)"></image>
            <view class="delete-btn" @tap.stop="deleteImage(index)">
              <uni-icons type="close" size="20" color="#fff"></uni-icons>
            </view>
          </view>
          <view class="upload-btn" @tap="chooseImage" v-if="postForm.images.length < 9">
            <uni-icons type="camera" size="32" color="#999"></uni-icons>
            <text>{{ postForm.images.length }}/9</text>
          </view>
        </view>
      </view>

      <!-- 标签选择 -->
      <view class="tag-section">
        <view class="section-title">添加标签</view>
        <scroll-view class="tag-scroll" scroll-x>
          <view class="tag-list">
          <view 
              class="tag-item"
              v-for="tag in tags"
              :key="tag.id"
              :class="{ active: selectedTags.includes(tag.id) }"
              @tap="toggleTag(tag)"
            >
              #{{ tag.name }}
            </view>
          </view>
        </scroll-view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { isLoggedIn } from '@/utils/auth'

export default {
  // 配置页面
  navigationStyle: 'custom',
  
  data() {
    return {
      postForm: {
      title: '',
      content: '',
      images: [],
        status: 1, // 1-已发布
        tagIds: []
      },
      errors: {
        title: '',
        content: ''
      },
      tags: [],
      selectedTags: [],
      isSubmitting: false
    }
  },

  computed: {
    canPublish() {
      return this.postForm.title.trim() && 
             this.postForm.content.trim() && 
             !this.errors.title && 
             !this.errors.content &&
             !this.isSubmitting
    }
  },

  onLoad() {
    this.loadTags()
  },

  methods: {
    goBack() {
      console.log('返回按钮被点击');
      // 如果用户已经输入内容，显示确认提示
      if (this.postForm.title.trim() || this.postForm.content.trim() || this.postForm.images.length > 0) {
        uni.showModal({
          title: '提示',
          content: '确定要放弃编辑吗？',
          success: (res) => {
            if (res.confirm) {
              console.log('用户确认返回');
              uni.navigateBack({
                delta: 1,
                fail: (err) => {
                  console.error('返回失败:', err);
                  // 如果返回失败，尝试跳转到社区首页
                  uni.switchTab({
                    url: '/pages/community/index'
                  });
                }
              });
            }
          }
        });
      } else {
        console.log('直接返回');
        uni.navigateBack({
          delta: 1,
          fail: (err) => {
            console.error('返回失败:', err);
            // 如果返回失败，尝试跳转到社区首页
            uni.switchTab({
              url: '/pages/community/index'
            });
          }
        });
      }
    },

    // 加载标签列表
    async loadTags() {
      try {
        const res = await this.$api.community.tags.hot()
        if (res.code === 200 && res.data) {
          this.tags = res.data
        }
      } catch (error) {
        console.error('加载标签失败:', error)
      }
    },

    // 验证标题
    validateTitle() {
      if (!this.postForm.title.trim()) {
        this.errors.title = '标题不能为空'
      } else if (this.postForm.title.length > 100) {
        this.errors.title = '标题长度不能超过100个字符'
      } else {
        this.errors.title = ''
      }
    },

    // 验证内容
    validateContent() {
      if (!this.postForm.content.trim()) {
        this.errors.content = '内容不能为空'
      } else {
        this.errors.content = ''
      }
    },

    // 选择图片
    async chooseImage() {
      if (!this.isLoggedIn()) {
        uni.navigateTo({
          url: '/pages/user/auth/login'
        })
        return
      }

      try {
        const res = await uni.chooseImage({
          count: 9 - this.postForm.images.length,
        sizeType: ['compressed'],
          sourceType: ['album', 'camera']
        })

        // 上传图片
        uni.showLoading({ 
          title: '上传中...',
          mask: true
        })
        
        for (const tempFilePath of res.tempFilePaths) {
          try {
            // 检查token
            const token = uni.getStorageSync('token')
            if (!token) {
              throw new Error('未登录或token已过期')
            }

            // 使用社区模块的上传接口
            const uploadRes = await this.$api.community.posts.uploadImage(tempFilePath)
            console.log('Upload Response:', uploadRes)
            
            // 直接使用返回的URL
            if (uploadRes) {
              this.postForm.images.push(uploadRes)
              console.log('添加图片URL到列表:', uploadRes)
            } else {
              throw new Error('上传失败，未获取到图片URL')
            }
            
          } catch (error) {
            console.error('上传图片失败:', error)
            uni.showToast({
              title: error.message || '图片上传失败',
              icon: 'none'
            })
            break // 如果上传失败，停止后续上传
          }
        }
      } catch (error) {
        console.error('选择图片失败:', error)
        uni.showToast({
          title: error.message || '选择图片失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },

    // 删除图片
    deleteImage(index) {
      this.postForm.images.splice(index, 1)
    },

    // 预览图片
    previewImage(index) {
      uni.previewImage({
        urls: this.postForm.images,
        current: index
      })
    },

    // 切换标签选择
    toggleTag(tag) {
      const index = this.selectedTags.indexOf(tag.id)
      if (index > -1) {
        this.selectedTags.splice(index, 1)
      } else {
        if (this.selectedTags.length < 3) {
          this.selectedTags.push(tag.id)
        } else {
          uni.showToast({
            title: '最多选择3个标签',
            icon: 'none'
          })
        }
      }
      this.postForm.tagIds = [...this.selectedTags]
    },

    // 发布帖子
    async handlePublish() {
      if (!this.canPublish) {
        uni.showToast({
          title: '请完善发布内容',
          icon: 'none'
        })
        return
      }
      
      if (!this.isLoggedIn()) {
        uni.navigateTo({
          url: '/pages/user/auth/login'
        })
        return
      }
      
      try {
        this.isSubmitting = true
        uni.showLoading({
          title: '发布中...',
          mask: true
        })
        
        // 验证必填字段
        if (!this.postForm.title.trim()) {
          throw new Error('请输入标题')
        }
        if (!this.postForm.content.trim()) {
          throw new Error('请输入内容')
        }
        
        // 构建发布数据
        const postData = {
          title: this.postForm.title.trim(),
          content: this.postForm.content.trim(),
          images: this.postForm.images || [], // 确保images字段存在
          tagIds: this.postForm.tagIds || [], // 确保tagIds字段存在
          status: 1 // 1-已发布
        }
        
        console.log('准备发布帖子:', postData)
        
        // 发布帖子
        const res = await this.$api.community.posts.create(postData)
        console.log('发布响应:', res)
        
        if (res.code === 200 && res.data) {
          uni.hideLoading()
        uni.showToast({
          title: '发布成功',
          icon: 'success'
        })
        
          // 延迟跳转到社区首页
        setTimeout(() => {
            uni.switchTab({
              url: '/pages/community/index'
            })
          }, 1500)
        } else {
          throw new Error(res.message || '发布失败')
        }
      } catch (error) {
        console.error('发布失败:', error)
        uni.hideLoading()
        uni.showToast({
          title: error.message || '发布失败',
          icon: 'none'
        })
      } finally {
        this.isSubmitting = false
      }
    },

    // 检查登录状态
    isLoggedIn() {
      const isLogged = isLoggedIn()
      if (!isLogged) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
      }
      return isLogged
    }
  }
}
</script>

<style lang="scss">
.post-container {
  min-height: 100vh;
  background-color: #fff;
  display: flex;
  flex-direction: column;
}

.nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background-color: #fff;
  padding-top: var(--status-bar-height);
  border-bottom: 1px solid #f5f5f5;
  
  .nav-content {
    position: relative;
    display: flex;
    align-items: center;
    height: 88rpx;
    padding: 0 30rpx;
    
    .nav-back {
      position: absolute;
      left: 30rpx;
      padding: 20rpx;
      background: none;
      border: none;
      outline: none;
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 1;
      
      &::after {
        border: none;
      }
      
      &.button-hover {
        opacity: 0.6;
      }
    }
    
    .title {
      flex: 1;
      text-align: center;
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .publish-btn {
      position: absolute;
      right: 30rpx;
      margin: 0;
      padding: 0 36rpx;
      height: 64rpx;
      line-height: 64rpx;
      font-size: 28rpx;
      color: #fff;
      background: linear-gradient(to right, #ff6b81, #ff4757);
      border-radius: 32rpx;
      border: none;
      box-shadow: 0 4rpx 8rpx rgba(255, 71, 87, 0.2);
      
      &[disabled] {
        background: #f5f5f5;
        color: #999;
        box-shadow: none;
      }
      
      &.loading {
        opacity: 0.8;
      }
    }
  }
}

.content-scroll {
  flex: 1;
  margin-top: calc(var(--status-bar-height) + 88rpx);
  padding: 30rpx;
}

.input-section {
  .title-input {
    font-size: 36rpx;
    color: #333;
    margin-bottom: 30rpx;
    font-weight: 500;
    padding: 20rpx 0;
    border-bottom: 1px solid #f5f5f5;
  }
  
  .content-input {
    width: 100%;
    font-size: 30rpx;
    color: #333;
    line-height: 1.8;
    min-height: 240rpx;
    padding: 20rpx 0;
  }
  
  .error-tip {
    font-size: 24rpx;
    color: #ff4757;
    margin: 8rpx 0;
  }
  
  .placeholder {
    color: #bbb;
  }
}

.upload-section {
  margin-top: 40rpx;
  
  .image-list {
    display: flex;
    flex-wrap: wrap;
    margin: -8rpx;
    
    .image-item,
    .upload-btn {
      width: calc(33.33% - 16rpx);
      margin: 8rpx;
      aspect-ratio: 1;
      border-radius: 8rpx;
      overflow: hidden;
    }
    
    .image-item {
      position: relative;
      background-color: #f8f8f8;
      
      image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      
      .delete-btn {
        position: absolute;
        top: 8rpx;
        right: 8rpx;
        width: 44rpx;
        height: 44rpx;
        background-color: rgba(0, 0, 0, 0.6);
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        backdrop-filter: blur(4px);
      }
    }
    
    .upload-btn {
      background-color: #f8f8f8;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      border: 2rpx dashed #ddd;
      transition: all 0.3s;
      
      &:active {
        background-color: #f0f0f0;
      }
      
      text {
        font-size: 24rpx;
        color: #999;
        margin-top: 12rpx;
      }
    }
  }
}

.tag-section {
  margin-top: 40rpx;
  padding-top: 30rpx;
  border-top: 1px solid #f5f5f5;
  
  .section-title {
    font-size: 28rpx;
    color: #333;
    font-weight: bold;
    margin-bottom: 20rpx;
    display: flex;
    align-items: center;
    
    &::before {
      content: '#';
      color: #ff4757;
      margin-right: 8rpx;
      font-size: 32rpx;
    }
  }
  
  .tag-scroll {
    white-space: nowrap;
    margin: 0 -30rpx;
    padding: 0 30rpx;
    
    .tag-list {
      display: inline-block;
      padding: 10rpx 0;
      
      .tag-item {
        display: inline-block;
        padding: 12rpx 24rpx;
        margin-right: 16rpx;
        font-size: 26rpx;
        color: #666;
        background-color: #f8f8f8;
        border-radius: 32rpx;
        transition: all 0.3s;
        
        &.active {
          color: #fff;
          background: linear-gradient(to right, #ff6b81, #ff4757);
        }
        
        &:last-child {
          margin-right: 30rpx;
        }
      }
    }
  }
}
</style> 